<template>
  <div class="list-table">
    <div class=" area-header">
      <span class="area-header-title">{{ $t('部门管理') }}</span>
    </div>
    <el-form :inline="true" @submit.native.prevent>
      <el-form-item :label="$t('部门名称')">
        <el-input
          v-model="queryParams.deptName"
          :placeholder="$t('部门名称')"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          class="filter-item"
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
        >{{ $t("搜索") }}</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['system:dept:edit']"
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >{{ $t("新增") }}</el-button>
      </el-col>
    </el-row>

    <el-table
      v-if="type !== ''"
      v-loading="loading"
      :data="deptList"
      row-key="deptId"
      :default-expand-all="type === 'tree'"
      border
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
      :lazy="type === 'table'"
      :load="onLoad"
      :expand-row-keys="expendKeys"
    >
      <el-table-column prop="deptName" :label="$t('部门名称')" />
      <el-table-column prop="orderNum" :label="$t('排序')" align="center" width="150" />
      <el-table-column :label="$t('创建时间')" align="center" prop="createTime" width="150">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('操作')" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-hasPermi="['system:dept:edit']"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >{{ $t('修改') }}</el-button>
          <el-button
            v-hasPermi="['system:dept:edit']"
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAdd(scope.row)"
          >{{ $t("新增") }}</el-button>
          <el-button
            v-if="scope.row.parentId != 0"
            v-hasPermi="['system:dept:remove']"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >{{ $t('删除') }}</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改对话框 -->
    <el-dialog :title="$t('部门')" :visible.sync="open" custom-class="dialogForm" width="70%" :close-on-click-modal="false">
      <div>
        <el-form ref="form" :model="form" :rules="rules" label-width="80px" class="dataForm">
          <el-row>
            <el-col v-if="form.parentId !== '0'" :span="12">
              <el-form-item :label="$t('上级部门')" prop="parentId">
                <DeptSelect v-model="form.parentId" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="$t('部门名称')" prop="deptName">
                <el-input v-model="form.deptName" :placeholder="$t('部门名称')" maxlength="30" show-word-limit />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="deptKey">
                <span slot="label">
                  {{ $t('部门标识') }}
                  <el-tooltip :content="$t('部门唯一标识,工作流中使用')" placement="top">
                    <i class="el-icon-question" />
                  </el-tooltip>
                </span>
                <el-input v-model="form.deptKey" :placeholder="$t('部门标识')" maxlength="30" show-word-limit />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="$t('部门类型')" prop="deptType">
                <dict-select
                  v-model="form.deptType"
                  dictionary="dept_type"
                  :placeholder="$t('部门类型')"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="$t('负责人')" prop="leader">
                <!--<el-input v-model="form.leader" placeholder="请输入负责人" maxlength="20" />-->
                <UserSelect v-model="form.leader" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="$t('部门副总')" prop="leadership">
                <!--<el-input v-model="form.leader" placeholder="请输入负责人" maxlength="20" />-->
                <UserSelect v-model="form.leadership" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="$t('分管领导')" prop="deputyGeneral">
                <!--<el-input v-model="form.leader" placeholder="请输入负责人" maxlength="20" />-->
                <UserSelect v-model="form.deputyGeneral" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="$t('联系电话')" prop="phone">
                <el-input v-model="form.phone" :placeholder="$t('联系电话')" maxlength="11" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="$t('邮箱')" prop="email">
                <el-input v-model="form.email" :placeholder="$t('邮箱')" maxlength="50" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="$t('显示排序')" prop="orderNum">
                <el-input-number v-model="form.orderNum" controls-position="right" :min="0" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="$t('是否为投资团队')" prop="isInvestmentTeam">
                <el-radio-group v-model="form.isInvestmentTeam">
                  <el-radio
                    v-for="dict in isInvestmentTeamOption"
                    :key="dict.dictValue"
                    :label="dict.dictValue"
                  >{{ $t(dict.dictLabel) }}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="$t('部门地址')" prop="address">
                <el-input v-model="form.address" :placeholder="$t('部门地址')" show-word-limit :maxlength="200" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer" style="text-align: right;">
          <el-button @click="cancel">{{ $t("取消") }}</el-button>
          <el-button type="primary" @click="submitForm">{{ $t("确定") }}</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDept, getDept, delDept, addDept, updateDept, listsDept } from '@/api/system/dept'

export default {
  name: 'Dept',
  data() {
    const checkDeptKeys = (rule, value, callback) => {
      if (value === '' || value === undefined || value === null) {
        callback(new Error('必填信息'))
      } else {
        listDept({}).then(response => {
          if (response.data !== null) {
            var _this = this
            var flag = true
            response.data.some(function(item) {
              if (_this.form.deptKey === item.deptKey) {
                if (_this.form.id === undefined || _this.form.id === null || _this.form.id === '') {
                  // 新增时校验
                  callback(new Error(_this.$t('部门标识已存在')))
                  flag = false
                  return true
                } else {
                  // 修改时校验
                  if (item.id !== _this.form.id) {
                    callback(new Error(_this.$t('部门标识已存在')))
                    flag = false
                    return true
                  }
                }
              }
            })
            if (flag) {
              callback()
            }
          } else {
            callback()
          }
        })
      }
    }
    return {
      // 遮罩层
      loading: true,
      // 表格树数据
      deptList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 状态数据字典
      statusOptions: [],
      // 部门类型字典
      deptTypeOption: [],
      // 默认展开的数据
      expendKeys: [],
      // 查询参数
      queryParams: {
        deptName: undefined,
        status: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        parentId: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ],
        deptName: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ],
        deptKey: [
          { required: true, validator: checkDeptKeys, trigger: 'blur' }
        ],
        orderNum: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ],
        email: [
          {
            type: 'email',
            message: this.$t('格式错误'),
            trigger: ['blur', 'change']
          }
        ],
        phone: [
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: this.$t('格式错误'),
            trigger: 'blur'
          }
        ]
      },
      isInvestmentTeamOption: [],
      // 加载类型（默认是tree）
      type: ''
    }
  },
  created() {
    if (this.$store.state.app.componentLayout) {
      this.type = this.$store.state.app.componentLayout
    } else {
      this.type = 'tree'
    }
    this.getList()
    this.getDicts('sys_normal_disable').then(response => {
      this.statusOptions = response.data
    })
    this.getDicts('sys_yes_no').then(response => {
      this.isInvestmentTeamOption = response.data
    })
    this.getDicts('dept_type').then(response => {
      this.deptTypeOption = response.data
    })
  },
  methods: {
    // 懒加载方法
    onLoad(tree, treeNode, resolve) {
      console.log(tree, treeNode, resolve)
      listsDept({ parentId: tree.id }).then(res => {
        if (res.data && res.data.length > 0) {
          res.data.forEach(dept => {
            dept.hasChildren = true
          })
        }
        resolve(res.data)
      })
    },
    /** 查询部门列表 */
    getList() {
      this.loading = true
      console.log(this.type)
      if (this.type === 'table') {
        if (!this.queryParams.parentId) {
          this.queryParams.parentId = '0'
        }
        this.queryParams.isSelectTop = ''
        listsDept(this.queryParams).then(response => {
          var expendKeys = []
          if (response.data && response.data.length > 0) {
            response.data.forEach(item => {
              item.hasChildren = true
              expendKeys.push(item.deptId)
            })
          }
          // this.deptList = response.data
          this.$set(this, 'deptList', response.data)
          this.$nextTick(() => {
            var eles = document.getElementsByClassName('el-table__expand-icon')
            for (let i = 0; i < eles.length; i++) {
              eles[i].click()
            }
          })
          // this.expendKeys = expendKeys
          this.loading = false
          // this.$store.dispatch('getSelTreeUser')
          // this.$store.dispatch('getDept')
        })
      } else {
        this.queryParams.parentId = undefined
        listDept(this.queryParams).then(response => {
          this.deptList = response.data
          this.loading = false
          this.$store.dispatch('getSelTreeUser')
          this.$store.dispatch('getDept')
        })
      }
    },
    // 字典状态字典翻译
    statusFormat(row, column) {
      console.log(column)
      return this.selectDictLabel(this.statusOptions, row.status)
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        deptId: undefined,
        parentId: undefined,
        deptName: undefined,
        orderNum: undefined,
        leader: undefined,
        phone: undefined,
        email: undefined,
        status: '0',
        address: undefined,
        isInvestmentTeam: undefined,
        deptType: undefined
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList()
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset()
      if (this.type === 'tree') {
        this.$store.dispatch('getDept')
      }
      if (row !== undefined) {
        this.form.parentId = row.deptId
      }
      this.open = true
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      if (this.type === 'tree') {
        this.$store.dispatch('getDept')
      }
      getDept(row.deptId).then(response => {
        this.form = response.data
        this.open = true
      })
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.deptId !== undefined) {
            updateDept(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess(this.$t('修改成功'))
                this.$store.dispatch('getDept')
                this.open = false
                this.getList()
              } else {
                this.msgError(response.msg)
              }
            })
          } else {
            addDept(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess(this.$t('新增成功'))
                this.open = false
                this.getList()
              } else {
                this.msgError(response.msg)
              }
            })
          }
        } else {
          this.locationError(document)
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm(this.$t('是否确认删除') + row.deptName + '?', this.$t('警告'), {
          confirmButtonText: this.$t('确定'),
          cancelButtonText: this.$t('取消'),
          type: 'warning'
        }).then(function() {
          return delDept(row.deptId)
        }).then(() => {
          this.getList()
          this.msgSuccess(this.$t('删除成功'))
        }).catch(function() {})
    }
  }
}
</script>
